import path from 'path'
import fs from "fs";
import { rollup } from 'rollup'
import commonjs from '@rollup/plugin-commonjs'
import url from '@rollup/plugin-url';
import { nodeResolve } from '@rollup/plugin-node-resolve'
import json from "@rollup/plugin-json";
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDefineOptions from 'unplugin-vue-define-options/rollup'
import esbuild from 'rollup-plugin-esbuild'
import postcss from 'rollup-plugin-postcss'
import {root, pkgRoot, outputEsm, outputCjs } from '../utils/paths'
import { target, generateExternal, generatePaths } from '../utils/rollup'
function genSingleInput() {
  let result = {
    'index': path.resolve(root, 'packages/index.js'),
  }
  const compsInputList = {}
  const hooksInputList = {}
  const directivesInputList = {}
  const utilsInputList = {}

  // components组件
  // const comps = fs.readdirSync(path.resolve(root, "packages/components"))
  //   .filter(item => {
  //     return fs.statSync(path.resolve(root + "/packages/components/", item)).isDirectory();
  //   });
  // comps.map(itemDirName => {
  //   let cPath = path.resolve(root + "/packages/components/" + itemDirName + "/index.js")
  //   compsInputList[`components/index`] = cPath
  // });
  // const comps = fs.readdirSync(path.resolve(root, "packages/components"))
  // comps.map((fileName,b,c,d) => {
  //   let cPath = path.resolve(root + "/packages/components/" + fileName)
  //   compsInputList[`${fileName.split('.')[0]}`] = cPath
  // });
  // console.log('components:',compsInputList)
  // hooks
  const hooks = fs.readdirSync(path.resolve(root, "packages/hooks"))
  hooks.map((fileName,b,c,d) => {
    let cPath = path.resolve(root + "/packages/hooks/" + fileName)
    hooksInputList[`${fileName.split('.')[0]}`] = cPath
  });
  // console.log('hooks:',hooksInputList)
  // directives
  const directives = fs.readdirSync(path.resolve(root, "packages/directives"))
  directives.map((fileName,b,c,d) => {
    let cPath = path.resolve(root + "/packages/directives/" + fileName)
    directivesInputList[`${fileName.split('.')[0]}`] = cPath
  });
  // console.log('directives:',directivesInputList)
  // utils
  const utils = fs.readdirSync(path.resolve(root, "packages/utils"))
  utils.map((fileName,b,c,d) => {
    let cPath = path.resolve(root + "/packages/utils/" + fileName)
    utilsInputList[`${fileName.split('.')[0]}`] = cPath
  });
  // console.log('utils:',utilsInputList)

  
  result = {
    ...result,
    ...compsInputList,
    ...hooksInputList,
    ...directivesInputList,
    ...utilsInputList
  }
  // console.log('result:',result)
  return result
}

export const buildModules = async () => {
  const input = [
    // root
    path.resolve(pkgRoot, 'index.js'),
    path.resolve(pkgRoot, 'hooks','index.js'),
    path.resolve(pkgRoot, 'directives','index.js'),
    // path.resolve(pkgRoot, 'store','index.js'),
    // path.resolve(pkgRoot, 'router','index.js'),
  ]
  // const input =  genSingleInput()
  const bundle = await rollup({
    input,
    plugins: [
      vueDefineOptions(),
      vue(),
      vueJsx(),
      url(),
      json(), 
      postcss(
        {
          inject: false, // 不直接注入样式到 JS 中，而是提取到单独的文件
          extract: true, // 提取 CSS 到 'bundle-name.css'
        }
      ),
      nodeResolve({ preferBuiltins: false }),
      commonjs(),
      esbuild({
        target,
        sourceMap: true,
      }),
    ],
    treeshake: false,
    external: generateExternal({ full: false }),
  })

  await Promise.all([
    bundle.write({
      format: 'esm',
      dir: outputEsm,
      exports: undefined,
      preserveModules: true,
      preserveModulesRoot: 'src',
      sourcemap: false,
      entryFileNames: `[name].mjs`,
    }),
    bundle.write({
      format: 'cjs',
      dir: outputCjs,
      exports: 'named',
      preserveModules: true,
      preserveModulesRoot: 'src',
      sourcemap: false,
      entryFileNames: `[name].js`,
      paths: generatePaths(),
    }),
  ])
}
